<?php
/**
 * Created by PhpStorm.
 * User: jocky
 * Date: 05/09/2017
 * Time: 22:32
 */
namespace backend\controllers;
use common\models\ar\MoneyWithdraw;
use common\models\ar\RealName;
use common\models\ar\SysConfig;
use common\models\ar\User;
use common\models\ar\ExchangeRate;
use common\models\MoneyDao;
use common\models\Pay;
use common\models\WithdrawDao;
class MoneyController extends BackendController
{
    public $enableCsrfValidation = false;
    /**
     * 出金
     *
     * @return string
     */
    public function actionWithdraw()
    {
        $req = \Yii::$app->request;
        $from = $req->get('from', date('Ymd', time() - 7 * 24 * 3600));
        $to = $req->get('to', date('Ymd'));
        $from = strtotime($from);
        $to = strtotime($to) + 24 * 3600;
        $RMB=ExchangeRate::findOne(['currency'=>'RMB']);
        $RMB=$RMB['exchange_rate'];
        return $this->renderPartial('withdraw', [
            'from' => $from,
            'to' => $to,
            'RMB'=>$RMB
        ]);
    }

    /**
     * 提交出金
     */
    public function actionWithdrawSubmit()
    {
        $uid = \Yii::$app->user->identity->id;
        $longinNames=\Yii::$app->user->identity->loginName;
        $req = \Yii::$app->request;
        $money = $req->post('money', 0);
//        if ($obj->withdraw_money_flag == 0) {
//            $code = 1005;
//            $msg = "限制出金";
//            exit(json_encode(['code' => $code, 'msg' => $msg]));
//        }
        //有未处理的记录
        // $sql = "SELECT COUNT(1) FROM `money_withdraw` WHERE `userID` = $uid AND `status` = 0";
        // $count = \Yii::$app->db->createCommand($sql)->queryScalar();
        // if ($count != 0) {
        //     $code = '1007';
        //     $msg = "您有未处理的出金记录";
        //     exit(json_encode(['code' => $code, 'msg' => $msg]));
        // }
        //当日出金次数限制
        $today = strtotime(date('Ymd'));
        $tmp = SysConfig::find()->where(['key' => 'max_withdraw_times'])->one();
        $maxTimes = $tmp->value;
        $tmp = SysConfig::find()->where(['key' => 'max_withdraw_money'])->one();
        $maxMoney = $tmp->value;
        //当日已出金次数
        $sql = "SELECT COUNT(1) FROM `money_withdraw` WHERE `userID` = $uid AND `withdraw_open_time` >= $today AND `status` = 3";
        $count = \Yii::$app->db->createCommand($sql)->queryScalar();
        if ($count >= $maxTimes) {
            $code = '1008';
            $msg = "每日出金次数限制为 " . $maxTimes . " 次";
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }
        if (!is_numeric($money) || !$money) {
            $code = 1004;
            $msg = "请输入正确的出金金额";
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        if ($money < 10) {
            $code = 1005;
            $msg = "出金金额不能小于10元";
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        if ($money > $maxMoney) {
            $code = 1005;
            $msg = "出金金额不能大于" . $maxMoney . "元";
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }
        //持仓或未生效的委托检测
        $sql="SELECT COUNT(1) FROM `hold_positions` WHERE `userID` = '".$uid."' ";
         $bool = \Yii::$app->db->createCommand($sql)->queryScalar();
         if ($bool!=0) {
             $code = '1004';
             $msg = "账户有持仓或未生效的委托";
             exit(json_encode(['code' => $code, 'msg' => $msg]));
         }
        //出金最大资金额
             $sql="SELECT SUM(tradeCost) FROM `user_broker_commission_record` WHERE `brokerId`=".$uid;
            $totalMoney = \Yii::$app->db->createCommand($sql)->queryScalar();
            $sql="SELECT SUM(grantMoney) FROM `user_broker_commission_grant_record` WHERE `brokerId`=".$uid;
            $out_money = \Yii::$app->db->createCommand($sql)->queryScalar();
            $totalMoney-=$out_money;
        if ($totalMoney < $money) {
            $code = '1007';
            $msg = "账户单笔最大可出金额为：" . $totalMoney;
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        $time = time();
        $ip = $req->getUserIP();
        $ua = $req->getUserAgent();
        $direction = 8; //出金
        $type = 2; //$money < $maxMoney ? 1 : 2;//1直接调代付接口,2由后台审核后调代付接口

        //记录
        $withdrawSN = uniqid('W');
        $withdrawObj = new MoneyWithdraw();
        $withdrawObj->attributes = [
            'withdraw_sn' => $withdrawSN,
            'userID' => $uid,
            'direction' => $direction,
            'money' => $money,
            'status' => 0,
            'withdraw_open_time' => $time,
            'loginName'=>$longinNames,
        ];
        if (!$withdrawObj->save(false)) {
            $code = '1007';
            $msg = "出金失败 | -" . $code;
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }
        //判断用户资金信息
         $bool = MoneyDao::inOut($uid, $uid, $direction, $money, $time, 1, $ip, $ua, '客户出金','1');
         if (!$bool) {
             $withdrawObj->status = 2;
             $withdrawObj->save();
             $code = '1010';
             $msg = "出金失败 | -" . $code;
             exit(json_encode(['code' => $code, 'msg' => $msg]));
         }
        //调用代付接口
        if ($type == 1) {
            $payObj = new Pay();
            $return = $payObj->withdraw($withdrawObj->id);

            if ($return['code'] == '000000') {
                $code = 1;
                $msg = "出金成功";
                $withdrawObj->status = 3;
            } else {
                $code = 0;
                $msg = "出金失败 | " . $return['code'];
                $withdrawObj->status = 2;
            }
            $withdrawObj->resp_code = $return['code'];
            $withdrawObj->withdraw_end_time = time();
            $withdrawObj->data_response = json_encode($return);
            $withdrawObj->save();

        } else {
            $code = '1';
            $msg = "出金已提交";
        }
        exit(json_encode(['code' => $code, 'msg' => $msg]));
    }

    /**
     * 取消出金
     */
    public function actionWithdrawCancel()
    {
        $uid = \Yii::$app->user->identity->id;
        $id = \Yii::$app->request->get('id', 0);
        $obj = MoneyWithdraw::findOne(['id'=>$id]);
        if (!$obj || $obj->userID != $uid) {
            $code = 1001;
            $msg = '权限不足';
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        if ($obj->status != 0) {
            $code = 1002;
            $msg = '状态已变化';
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        switch ($obj->direction) {
            case 2:
                $direction = 1;
                break;
            case 8:
                $direction = 9;
                break;
            case 18:
                $direction = 17;
                break;
            case 102:
                $direction = 101;
                break;
            default:
                $code = 1003;
                $msg = '类型错误';
                exit(json_encode(['code' => $code, 'msg' => $msg]));
                break;
        }

        $time = time();
        $ip = \Yii::$app->request->getUserIP();
        $ua = \Yii::$app->request->getUserAgent();

        $bool = MoneyDao::inOut($uid, $uid, $direction, $obj->money, $time, 1, $ip, $ua, '用户取消','1');
        if (!$bool) {
            $code = 0;
            $msg = "操作失败";
        } else {
            $obj->status = 5;
            $obj->withdraw_start_time = $time;
            $obj->withdraw_end_time = $time;
            $obj->data_response = json_encode(['msg' => '用户取消']);
            $obj->save(false);
            $code = 1;
            $msg = "操作成功";
        }

        exit(json_encode(['code' => $code, 'msg' => $msg]));
    }

    /**
     * 出金历史
     */
    public function actionWithdrawHistory()
    {
        $uid = \Yii::$app->user->identity->id;
        $req = \Yii::$app->request;
        $status = $req->get('status', -1);//状态
        $from = $req->get('from', date('Ymd', time() - 7 * 24 * 3600));
        $to = $req->get('to', date('Ymd'));
        $from = strtotime($from);
        $to = strtotime($to) + 24 * 3600;
        $pageNo = $req->get('pageNo', 1);
        $pageSize = 15;
        $data = WithdrawDao::history($status, $uid, $from, $to, $pageNo, $pageSize,'1');
        $pageTotal = ceil($data['total'] / $pageSize);
        if ($pageTotal == 0) {
            $pageNo = 1;
        } else {
            if ($pageNo > $pageTotal) {
                $pageNo = $pageTotal;
                $data = WithdrawDao::history($status, $uid, $from, $to, $pageNo, $pageSize,'1');
            }
        }
        $data['pageNo'] = $pageNo;
        $data['pageTotal'] = $pageTotal;

        exit(json_encode($data));
    }
}
